//
//  HotWordAppDelegate.m
//  HotWord
//
//  Created by Rainbow on 8/22/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HotWordAppDelegate.h"
#import "ServiceHelper.h"
#import "CacheData.h"
#import "PersistenceData.h"
#import "MainMenuViewController.h"
#import "HomePageViewController.h"
#import "UserManager.h"
#import "MessageManager.h"


@implementation HotWordAppDelegate
@synthesize MainToolBar = _MainToolBar;
@synthesize background;

@synthesize window=_window;

static HotWordAppDelegate *appDelegate = nil;

+ (HotWordAppDelegate *)sharedAppDelegate
{
    return appDelegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    appDelegate = self;
    
    [self.window makeKeyAndVisible];
    self.window.backgroundColor = [UIColor blackColor];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Default.png"]] autorelease];
    imageView.frame = CGRectMake(0, 0, 320, 480);
    imageView.tag = 88;
    [self.window addSubview:imageView];
    [self initData];
    
    return YES;
}


-(void)showUI
{
    [[self.window viewWithTag:88] removeFromSuperview];
    HomePageViewController *homePageViewController = [[HomePageViewController alloc] init];
    navigationController = [[UINavigationController alloc] initWithRootViewController:homePageViewController];
    [homePageViewController release];
    
    _touchMaskView = [[TouchMaskView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _touchMaskView.hidden = YES;
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [navigationController setNavigationBarHidden:YES];
    self.sliderView = (SliderView *)[[[NSBundle mainBundle] loadNibNamed:@"SliderView" owner:self options:nil] objectAtIndex:0];
    _sliderView.height = self.window.height;
    [self.window addSubview:_sliderView];

    self.window.rootViewController = navigationController;
    [self.window addSubview:self.MainToolBar];
    [((UIButton *)[self.MainToolBar viewWithTag:333])setHidden:YES];
    [self.window bringSubviewToFront:self.MainToolBar] ;
    [self.window addSubview:background];
    [self.window sendSubviewToBack:background];
}

- (void)tapGestureRecognizerAction:(UITapGestureRecognizer *)tapGestureRecognizer
{
    [self showSliderView:NO];
}

- (void)swipeRootView:(UISwipeGestureRecognizer *)swipeGestureRecognizer
{
    [self showSliderView:NO];
}

-(void)initData
{
    [self showUI];
    
    locationManager = [[CLLocationManager alloc] init];
    
    if (![CLLocationManager locationServicesEnabled])
    {
        NSLog(@"User has opted out of location services");
    }
    
    else
    {
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        locationManager.distanceFilter = 5.0f; // in meters
        [locationManager startUpdatingLocation];
    }
    
    [[MessageManager sharedManager] sendReceiveMessage];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    if ([UserManager sharedManager].currentUser.userId) {
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeResetNews WithParameters:[NSDictionary dictionaryWithObject:[UserManager sharedManager].currentUser.userId forKey:@"id"] AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
    }
    
    if ([USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN] == nil || [@"" isEqualToString:[USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN]]) {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
    }
    else{
        
        if ([UserManager sharedManager].currentUser.userId) {
            NSMutableDictionary *pushParams = [NSMutableDictionary dictionary];
            [pushParams setObject:[USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN] forKey:@"token"];
            [pushParams setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
            [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUploadToken WithParameters:pushParams AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
        }
    }
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:version forKey:@"v"];
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeCheckUpdate WithParameters:params AndCallBackScope:self AndSuccessSel:@"checkUpdate:" AndFailedSel:@"checkUpdateFailed"];
    
}

- (void)checkUpdateFailed
{
    
}

- (void)checkUpdate:(NSObject *)result
{
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        _upgradeInfo = [[dic objectForKey:@"data"] retain];
        NSString *content = [UtilHelper getStringValue:[_upgradeInfo objectForKey:@"content"]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"升级提醒" message:content delegate:self cancelButtonTitle:@"下次再说" otherButtonTitles:@"前往升级", nil];
        [alertView show];
        [alertView release];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSString *updateUrl = [UtilHelper getStringValue:[_upgradeInfo objectForKey:@"url"]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updateUrl]];
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken 
{   
	NSString *str = [devToken description]; 
    str = [str substringWithRange:NSMakeRange(1, 71)];
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
	[USER_DEFAULT setObject:str forKey:USERDEFAULT_DEVICE_TOKEN];
	[USER_DEFAULT synchronize];
    
    if ([UserManager sharedManager].currentUser.userId) {
        NSMutableDictionary *pushParams = [NSMutableDictionary dictionary];
        [pushParams setObject:[USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN] forKey:@"token"];
        [pushParams setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUploadToken WithParameters:pushParams AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
	NSLog(@"Location manager error: %@",[error description]);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
	CLLocationCoordinate2D location2D = newLocation.coordinate;
    [UserManager sharedManager].currentLocation2D = location2D;
    if ([UserManager sharedManager].currentUser) {
        [UserManager sharedManager].currentUser.longitude = [NSString stringWithFormat:@"%f", location2D.longitude];
        [UserManager sharedManager].currentUser.latitude = [NSString stringWithFormat:@"%f", location2D.latitude];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:[UserManager sharedManager].currentUser.latitude forKey:@"latitude"];
        [params setObject:[UserManager sharedManager].currentUser.longitude forKey:@"longitude"];
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUpdateGeo WithParameters:params AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
    }
	[locationManager stopUpdatingLocation];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    [[PersistenceData sharedData] syncLetterStatus:[CacheData sharedData].selectedLetter];
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    
    [[PersistenceData sharedData] syncLetterStatus:[CacheData sharedData].selectedLetter];
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

#pragma mark - Public

- (void)showSliderView:(BOOL)isShow
{
//    if (isShow)
//    {
//        [self.window bringSubviewToFront:_sliderView];
//    }
    
    _isSliderViewShowing = isShow;
    [UIView animateWithDuration:0.4f animations:^{
        if (isShow)
        {
            self.window.rootViewController.view.left = _sliderView.width;
        }
        else
        {
            self.window.rootViewController.view.left = 0;
        }
    }];
    
    _touchMaskView.hidden = !_isSliderViewShowing;
    
}

- (void)setRootViewLeft:(CGFloat)left
{
    self.window.rootViewController.view.left = left;
}


- (void)dealloc
{
    [_upgradeInfo release];
    [locationManager release];
    [_window release];
    [_MainToolBar release];
    [navigationController release];
    [_sliderView release];
    [_touchMaskView release];
    [super dealloc];
}

@end
